import { checkMainType } from '@/pages/InventoryAnalysis/components/ApiService';
import type { FowardSearchRenderB } from '@/pages/InventoryAnalysis/components/search/SearchRenderB';
import SearchRenderB from '@/pages/InventoryAnalysis/components/search/SearchRenderB';
import {
  useProviderDataHook,
  useProviderGoodsDataHook,
} from '@/pages/InventoryAnalysis/providers/useProviderDataHook';
import {
  getGoodsMoonTableListApi,
  getTableListApi,
  getTreeListApi,
} from '@/services/InventoryAnalysis/providers';
import { useModel } from '@@/exports';
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import CpasLayout from '~/public/cpas-business/cpas-table/CpasLayout';

const MONTH_CONFIG = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'];
const InventoryAnalysisProviderMoonAnalysis: React.FC = (props: any) => {
  const pageType = props.params?.type;
  const globalModel = useModel('@@initialState') as any;
  const dbname = globalModel?.initialState?.curPart?.dbname;
  // 页面首次默认账套
  const ztModel = useModel('ztModel');
  // ----------------------------- 获取默认年度，和组件行为保持一致 , 用于首次请求接口
  const defaultDataID = ztModel.getDefaultValue();
  // 表体数据
  const [tableData, setTableData] = useState<any[]>([]);
  //树节点数据
  const [treeListData, setTreeListData] = useState<any[]>([]);
  //选择年度
  const [dateId, setDateId] = useState<any>(defaultDataID);
  //排名
  const [ranking, setRanking] = useState<any>(10);
  // 查询条件
  const SearchRenderBRef = useRef<FowardSearchRenderB | null>(null);
  // 当选选中的树节点
  const [selectTreeNode, setSelectTreeNode] = useState<any>(null);

  const LayoutRef = useRef<any>(null);

  /**
   * 获取树列表
   */
  const getTreeList = async () => {
    try {
      const res: any = await getTreeListApi({
        dbname,
      });
      const data = res?.data;
      console.log(data, 'data---');
      if (data && data.length) {
        setTreeListData([...data]);
        if (!selectTreeNode?.id) {
          setSelectTreeNode(data[0]);
        }
      } else {
        setTreeListData([]);
      }
    } catch (e) {
      throw e;
    }
  };
  /**
   * 获取table数据
   * @param dataID
   * @param ranking
   */
  const getTableList = async (dataID = '2022', rankingVal = null, typeName = null) => {
    // 检测业务类型是否存在
    const result = await checkMainType(dbname, '采购');
    if (!result) {
      return;
    }
    try {
      const res: any = await getTableListApi({
        dbname,
        dataID,
        ranking: rankingVal,
        dates: MONTH_CONFIG,
        dataField: ['Qty', 'Money'],
        typeName: typeName === '全部' ? null : typeName,
      });
      setTableData(res?.data);
    } catch (e) {
      throw e;
    }
  };
  useEffect(() => {
    getTreeList();
  }, []);

  /**
   * 刷新默认账套
   */
  useEffect(() => {
    ztModel.refresh();
  }, []);

  useEffect(() => {
    setDateId(defaultDataID);
  }, [defaultDataID]);

  /**
   * 首次，加载表格数据
   */
  useEffect(() => {
    if (selectTreeNode) {
      console.log(selectTreeNode, 'selectTreeNode---');
      getTableList(dateId, ranking, selectTreeNode.name);
    }
  }, [dbname, dateId, selectTreeNode, ranking]);
  /**
   * 表头数据
   */
  const { tableColumnData } = useProviderDataHook(MONTH_CONFIG, 'moon');

  /**
   * 详情页表头数据
   */
  const { tableColumnData: detailTableColumnData } = useProviderGoodsDataHook(MONTH_CONFIG, 'moon');

  /**
   * 获取查询表单数据
   */
  const getSearchFormValue = useCallback(() => {
    const searchValues = SearchRenderBRef.current?.getFormSearchValues() || null;
    if (!searchValues) {
      return {};
    }
    return {
      ...searchValues,
    };
  }, []);
  const devToolLeftbar = useMemo(() => {
    return [
      {
        widget: 'dxButton',
        options: {
          text: '查看全部明细',
          type: 'default',
          onClick: () => {
            console.log('查看明细', SearchRenderBRef.current?.getFormSearchValues());
            if (LayoutRef.current) {
              LayoutRef.current.addTab('查看全部明细');
            }
          },
        },
      },
    ];
  }, []);

  /**
   * 查看全部明细：加载全部的devgrid数据
   */
  const loadAllDevGridData = useCallback(async () => {
    try {
      const searchValues = SearchRenderBRef.current?.getFormSearchValues() || null;
      const ztValue: any = searchValues?.ztValue;
      const rankingValue: any = searchValues?.ranking;
      const res: any = await getGoodsMoonTableListApi({
        dbname,
        dataID: ztValue,
        ranking: rankingValue,
        dates: MONTH_CONFIG,
        dataField: ['Qty', 'Money'],
      });
      return {
        dataSource: res?.data,
        // columnData: tableColumnData,
      };
    } catch (e) {
      console.log(e);
      return {
        dataSource: [],
        columnData: [],
      };
      throw e;
    }
  }, []);
  /**
   * 双击加载单条的devGrid数据
   */
  const loadSingleDevGridData = useCallback(async (rowData: any) => {
    try {
      const searchValues = SearchRenderBRef.current?.getFormSearchValues() || null;
      const ztValue: any = searchValues?.ztValue;
      const rankingValue: any = searchValues?.ranking;
      const supplierID = rowData?.supplierID ? rowData?.supplierID : null;
      const res: any = await getGoodsMoonTableListApi({
        dbname,
        dataID: ztValue,
        ranking: rankingValue,
        dates: MONTH_CONFIG,
        dataField: ['Qty', 'Money'],
        supplierID,
      });
      return {
        dataSource: res?.data,
        // columnData: tableColumnData,
      };
    } catch (e) {
      console.log(e);
      return {
        dataSource: [],
        columnData: [],
      };
      throw e;
    }
  }, []);

  /**
   * 点击树节点回调
   */
  const onTreeClickCallback = (e: any) => {
    const rowData = e.itemData;
    console.log(rowData, 'treeClickCallback');
    setSelectTreeNode(e.node.itemData);
  };
  /**
   * 刷新回调
   */
  const onRefreshBtnCallback = async () => {
    const searchValues = SearchRenderBRef.current?.getFormSearchValues() || null;
    console.log('onRefreshBtnCallback');
    const ztValue: any = searchValues?.ztValue;
    const rankingVal: any = searchValues?.ranking;
    await getTreeList();
    await getTableList(ztValue, rankingVal, selectTreeNode?.name);
  };
  /**
   * 渲染查询条件
   * @param searchFormDisabled
   * @returns
   */
  function renderSearch() {
    return <SearchRenderB ref={SearchRenderBRef} ztValue={null} ranking={10} dbname={dbname} setUserTypeCallback={onRefreshBtnCallback} />;
  }
  /**
   * 查询按钮回调
   * @returns
   */
  async function searchCallback() {
    const searchValues = SearchRenderBRef.current?.getFormSearchValues() || null;
    if (!searchValues) {
      return;
    }
    const ztValue: any = searchValues?.ztValue;
    const rankingValue: any = searchValues?.ranking;
    if (ztValue === dateId && rankingValue === ranking) {
      await onRefreshBtnCallback();
    } else {
      setDateId(ztValue);
      setRanking(rankingValue);
    }
  }
  return (
    <>
      <div
        style={{
          border: '0px solid green',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
        }}
      >
        <CpasLayout
          ref={LayoutRef}
          pageType={pageType}
          treeListData={treeListData}
          tableColumnsData={tableColumnData}
          detailTableColumnData={detailTableColumnData}
          tableData={tableData}
          renderSearch={renderSearch}
          searchElement={SearchRenderB}
          detailKey={'supplierName'}
          getSearchFormData={getSearchFormValue}
          devToolLeftItem={devToolLeftbar}
          isLeftTree={true}
          searchClickCallback={searchCallback}
          treeClickCallback={onTreeClickCallback}
          refreshBtnCallback={onRefreshBtnCallback}
          loadAllDevGridData={loadAllDevGridData}
          loadSingleDevGridData={loadSingleDevGridData}
          parentRef={LayoutRef}
        />
      </div>
    </>
  );
};

export default InventoryAnalysisProviderMoonAnalysis;
